import path from 'path';
import crypto from 'crypto';
import configTool from '../../../com/configTool';
import readFromDB from '../Util/readFromDB';
import readFromNet from '../Util/readFromNet';
import initDB from '../Util/initDB';
import saveToDB from '../Util/saveToDB';
import saveToFile from '../Util/saveToFile';
import readFromDisk from '../Util/readFromDisk';
import imgMD5 from '../../../img/imgMD5';
import ImgMD5 from '../../../img/imgMD5';

let Loading = true;
const DBName = 'tianditu-wmts';

//嘉兴渤海公司，天地图申请的密钥
let TDU_Key = '';
// 矢量底图
const vec_wUrl = 'http://t0.tianditu.gov.cn/vec_w/wmts?service=wmts&request=GetTile&version=1.0.0' +
    '&LAYER=vec&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}' +
    '&style=default&format=tiles&tk=';
// 矢量注记
const cva_w = 'http://t0.tianditu.gov.cn/cva_w/wmts?service=wmts&request=GetTile&version=1.0.0' +
    '&LAYER=cva&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}' +
    '&style=default.jpg&tk=';
// 影像底图
const img_w = 'http://t0.tianditu.gov.cn/img_w/wmts?service=wmts&request=GetTile&version=1.0.0' +
    '&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}' +
    '&style=default&format=tiles&tk=';
// 影像注记
const cia_w = 'http://t0.tianditu.gov.cn/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0' +
    '&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}' +
    '&style=default.jpg&tk=';
// 地形晕渲
const ter_w = 'http://t0.tianditu.gov.cn/ter_w/wmts?service=wmts&request=GetTile&version=1.0.0' +
    '&LAYER=ter&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}' +
    '&style=default&format=tiles&tk=';
// 路网注记
const cta_w = 'http://t0.tianditu.gov.cn/cta_w/wmts?service=wmts&request=GetTile&version=1.0.0' +
    '&LAYER=cta&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}' +
    '&style=default&format=tiles&tk=';
// 国界省界
const ibo_w = 'https://t0.tianditu.gov.cn/ibo_w/wmts?service=wmts&request=GetTile&version=1.0.0' +
    '&LAYER=ibo&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}' +
    '&style=default&format=tiles&tk=';

enum MapType {
    vec_w = 'vec_w',
    cva_w = 'cva_w',
    img_w = 'img_w',
    cia_w = 'cia_w',
    ter_w = 'ter_w',
    cta_w = 'cta_w',
    ibo_w = 'ibo_w',
}

let TianDiTu = {
    async init() {
        if (Loading) {
            Loading = false;
            await configTool.init();
            configTool.preservableONDB() && await initDB(DBName);
            this.setTDU_Key(configTool.config.TianDiTu.tk);
            console.info('TianDiTu 令牌：' + TDU_Key);
        }
    },
    setTDU_Key(key: string) {
        TDU_Key = key;
    },
    // 获取瓦片
    async getTileFileBuffer(mapType: MapType, TileMatrix: number, TileCol: number, TileRow: number) {
        await this.init();
        let err, buffer, dataSource;

        let templateUrl = '';
        if (mapType) {
            switch (mapType) {
                case MapType.vec_w:
                    templateUrl = vec_wUrl;
                    break;
                case MapType.cva_w:
                    templateUrl = cva_w;
                    break;
                case MapType.img_w:
                    templateUrl = img_w;
                    break;
                case MapType.cia_w:
                    templateUrl = cia_w;
                    break;
                case MapType.ter_w:
                    templateUrl = ter_w;
                    break;
                case MapType.cta_w:
                    templateUrl = cta_w;
                    break;
                case MapType.ibo_w:
                    templateUrl = ibo_w;
            }
        }


        const url = templateUrl
            .replace('{TileMatrix}', TileMatrix.toString())
            .replace('{TileRow}', TileRow.toString())
            .replace('{TileCol}', TileCol.toString()) + TDU_Key;

        const relativePath = `\\${mapType}\\${TileMatrix}\\${TileCol}\\${TileRow}.png`;
        const fileSavePath = path.join(configTool.appBasePath, `temp/fileOut/${DBName}`, relativePath);

        // 从本地文件夹中获取文件
        [err, buffer, dataSource] = await readFromDisk({fileSavePath, err, buffer, dataSource});

        // 从数据库中获取文件
        [err, buffer, dataSource] = await readFromDB({DBName, relativePath, err, buffer, dataSource});

        // 从网络获取
        [err, buffer, dataSource] = await readFromNet({
            url, headers: {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:125.0) Gecko/20100101 Firefox/125.0',
                'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
                'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
                'Upgrade-Insecure-Requests': '1',
                'Sec-Fetch-Dest': 'document',
                'Sec-Fetch-Mode': 'navigate',
                'Sec-Fetch-Site': 'none',
                'Sec-Fetch-User': '?1'
            }, err, buffer, dataSource
        });


        if (buffer) {
            const md5Str = crypto.createHash('md5').update(buffer).digest('hex');
            if (md5Str !== imgMD5.emptyPng) {
                dataSource !== 'DB' && configTool.preservableONDB() && saveToDB({DBName, relativePath, buffer}).then();
                dataSource === 'Net' && configTool.preservableONFile() && saveToFile(fileSavePath, buffer).then();
            }
        } else {
            dataSource = 'nullServer';
            if (mapType === 'vec_w' || mapType === 'img_w' || mapType === 'ter_w') {
                buffer = ImgMD5.emptyBuffer;
            } else {
                buffer = ImgMD5.transparentBuffer;
            }
        }

        return [err, buffer, dataSource];
    }
};

export default TianDiTu;
